package com.zang.quartz.service;

import com.zang.quartz.task.MailJob;
import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;

/**
 * @author Zhang Qiang
 * @Date 2019/9/2 11:17
 */
public class QuartzService {

    public void startTask() throws SchedulerException {
        //调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        //定时器 触发器
        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).withRepeatCount(10))
                .build();

        //定义Job 任务
        JobDetail jobDetail = JobBuilder.newJob(MailJob.class).withIdentity("myJob").build();
        scheduler.start();
        scheduler.scheduleJob(jobDetail, trigger);

    }

    /**
     * cron 表达式
     *
     * @param cron
     * @return
     */
    public void startTask(String cron) throws SchedulerException {
        JobDetail jobDetail = JobBuilder.newJob(MailJob.class).withIdentity("cronJob").build();
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("cronTrigger").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
        StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
        Scheduler stdScheduler = stdSchedulerFactory.getScheduler();
        stdScheduler.start();
        stdScheduler.scheduleJob(jobDetail,trigger);

    }

}
